package com.ton.utils.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class HttpUtils {

    //无参方式
    public static String get(String url,Map<String,String> header,Map<String,Object> params) {
        return getWithParams(url, header, params);
    }
    public static String post(String url,Map<String,String> header,Map<String,Object> params) {
        return postWithParams(url, header, params);
    }

    //有参方式
    public static String getWithParams(String url,Map<String,String> headers, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        HttpGet httpGet = null;
        try {
            // 创建Get请求
            url = joinParam(url, params);
            httpGet = new HttpGet(url);
            for(String key: headers.keySet()){
                httpGet.addHeader(key,headers.get(key));
            }
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(5000) //服务器响应超时时间
                    .setConnectTimeout(5000) //连接服务器超时时间
                    .build();
            httpGet.setConfig(requestConfig);
            // 由客户端执行(发送)Get请求
            //httpClient.close();
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                String json = EntityUtils.toString(responseEntity);
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + json);
                return json;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String postWithParams(String url,Map<String,String> headers, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            // 创建Post请求
            //  url = joinParam(url, params);
            HttpPost httpPost = new HttpPost(url);
            for(String key: headers.keySet()){
                httpPost.addHeader(key,headers.get(key));
            }
            //“application/json”、"application/x-www-form-urlencoded"

            //httpPost.
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(2000) //服务器响应超时时间
                    .setConnectTimeout(2000) //连接服务器超时时间
                    .build();

             //设置参数
              if (params != null) {
                 List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                 for (Map.Entry<String, Object> entry : params.entrySet()) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
                 }
                 httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
              }

            httpPost.setConfig(requestConfig);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                String json = EntityUtils.toString(responseEntity);
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + json);
                return json;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static String joinParam(String url, Map<String, Object> params) {
        if (params == null || params.size() == 0) {
            return url;
        }

        StringBuilder urlBuilder = new StringBuilder(url);
        urlBuilder.append("?");

        int counter = 0;
        for (Map.Entry<String,Object> entry : params.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (key == null) {
                continue;
            }

            if (counter == 0) {
                urlBuilder.append(key).append("=").append(value);
            } else {
                urlBuilder.append("&").append(key).append("=").append(value);
            }
            counter++;
        }

        return urlBuilder.toString();
    }

    public static String toJson(HttpEntity httpEntity){
        String json = "";
        try {
             json = EntityUtils.toString(httpEntity);
             return json;
        }catch (Exception e){
            log.error("返回对象转JSON失败!");
            return json;
        }
    }

}